package com.fhz.bluetooth_test

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.RadioGroup.OnCheckedChangeListener
import android.widget.Switch
import com.fhz.bluetooth_test.databinding.ActivityMainBinding
import java.io.IOException

class MainActivity : AppCompatActivity() {
    lateinit var bluetoothAdapter:BluetoothAdapter
    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)


        requestPermissions(arrayOf(Manifest.permission.BLUETOOTH_CONNECT
            ,Manifest.permission.BLUETOOTH
            ,Manifest.permission.BLUETOOTH_SCAN
            ,Manifest.permission.ACCESS_FINE_LOCATION
            ,Manifest.permission.ACCESS_COARSE_LOCATION
        ),100)

        val systemService = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager

        bluetoothAdapter = systemService.adapter

        binding.openandclose.setOnCheckedChangeListener { buttonView, isChecked ->
            if(isChecked){
                bluetoothAdapter.enable()

                val pairedDevices: Set<BluetoothDevice>? = bluetoothAdapter?.bondedDevices
                pairedDevices?.forEach { device ->
                    val deviceName = device.name
                    val deviceHardwareAddress = device.address // MAC address
                    print(deviceName)
                    print("----")
                    println(deviceHardwareAddress)
                }
            }else{
                bluetoothAdapter.disable()
            }
        }

        val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //开始扫描
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描结束
        registerReceiver(receiver, filter)

        binding.tvBlue.setOnClickListener {
            bluetoothAdapter.startDiscovery()
        }

    }
    private val receiver = object : BroadcastReceiver() {

        @SuppressLint("MissingPermission")
        override fun onReceive(context: Context, intent: Intent) {
            val action: String? = intent.action
            println(action)
            when(action) {
                BluetoothDevice.ACTION_FOUND -> {
                    // Discovery has found a device. Get the BluetoothDevice
                    // object and its info from the Intent.
                    val device: BluetoothDevice? =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    val deviceName = device?.name
                    val deviceHardwareAddress = device?.address // MAC address
                    print(deviceName)
                    print("----")
                    println(deviceHardwareAddress)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)

    }

//    private inner class ConnectThread(device: BluetoothDevice) : Thread() {
//
//        private const val TAG = "MainActivity"
//        private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
////            device.createRfcommSocketToServiceRecord(MY_UUID)
//        }

//        public override fun run() {
            // Cancel discovery because it otherwise slows down the connection.
//            bluetoothAdapter?.cancelDiscovery()
//
//            mmSocket?.let { socket ->
//                // Connect to the remote device through the socket. This call blocks
//                // until it succeeds or throws an exception.
//                socket.connect()
//
//                // The connection attempt succeeded. Perform work associated with
//                // the connection in a separate thread.
//                manageMyConnectedSocket(socket)
//            }
//        }

        // Closes the client socket and causes the thread to finish.
//        fun cancel() {
//            try {
//                mmSocket?.close()
//            } catch (e: IOException) {
//                Log.e(TAG, "Could not close the client socket", e)
//            }
//        }
//    }


}


